import axios from 'axios'

const request = axios.create({
    baseURL: 'http://localhost:8081/api', // 走网关
    timeout: 5000
})

// 添加请求拦截器，自动带上 token
request.interceptors.request.use(config => {
    const token = localStorage.getItem('token')
    if (token) {
        config.headers['Authorization'] = 'Bearer ' + token
    }
    return config
}, error => {
    return Promise.reject(error)
})

request.interceptors.response.use(
  response => response,
  error => {
    if (error.response && error.response.status === 401) {
      alert('登录已过期，请重新登录')
      localStorage.removeItem('token')
      window.location.reload() // 或跳转到登录页
    }
    return Promise.reject(error)
  }
)

export default request